package convert.types;


import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import convert.AbstractToPdf;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 图片转PDF
 * <br>
 * Created by Hong 2024/7/4
 **/
public class ImageToPdf extends AbstractToPdf {

    private final Document document = new Document(PageSize.A4, 20, 20, 20, 20);
    private final InputStream inputStream;

    public ImageToPdf(InputStream inputStream) throws Exception {
        this.inputStream = inputStream;
    }

    @Override
    public void init() {

    }

    @Override
    protected void fontSettings() {

    }

    @Override
    public void toPdf(OutputStream outputStream) throws Exception {
        PdfWriter.getInstance(document, outputStream);
        document.open();
        document.newPage();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int length;
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        while (-1 != (length = bufferedInputStream.read(bytes))) {
            byteArrayOutputStream.write(bytes, 0, length);
        }

        Image image = Image.getInstance(byteArrayOutputStream.toByteArray());
        float height = image.getHeight();
        float width = image.getWidth();
        float percent;
        // 设置像素或者长宽高,将会影响图片的清晰度，因为只是对图片放大或缩小
        if (height > width) {
            percent = PageSize.A4.getHeight() / height * 100;
        } else {
            percent = PageSize.A4.getWidth() / width * 100;
        }
        image.setAlignment(Image.MIDDLE);
        image.scalePercent(percent);

        document.add(image);
    }

    @Override
    public void close() {
        if (document != null) {
            document.close();
        }
    }
}
